package org.goodsmanager.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.entity.Category;
import org.goodsmanager.entity.Product;
import org.goodsmanager.service.CategoryService;
import org.goodsmanager.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

/**
 * 用户界面控制器
 * 处理面向普通用户的界面请求，与管理后台分离
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Controller
@RequestMapping("/shop")
@RequiredArgsConstructor
public class ShopController {

    private final ProductService productService;
    private final CategoryService categoryService;

    /**
     * 商城首页
     */
    @GetMapping({"", "/"})
    public String index(Model model) {
        try {
            // 获取所有分类
            List<Category> categories = categoryService.getAllCategories();
            
            // 获取热销商品
            List<Product> hotProducts = productService.getHotProducts(8);
            
            // 获取新品
            List<Product> newProducts = productService.getNewProducts(8);
            
            // 获取推荐商品（随机选择）
            List<Product> recommendedProducts = productService.getRecommendedProducts(8);
            
            model.addAttribute("categories", categories);
            model.addAttribute("hotProducts", hotProducts);
            model.addAttribute("newProducts", newProducts);
            model.addAttribute("recommendedProducts", recommendedProducts);
            
            return "shop/index";
        } catch (Exception e) {
            log.error("加载商城首页失败", e);
            model.addAttribute("error", "加载商城首页失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 商品列表页面
     */
    @GetMapping("/products")
    public String productList(Model model,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "12") int size,
                             @RequestParam(required = false) String keyword,
                             @RequestParam(required = false) String categoryId,
                             @RequestParam(required = false) String sortBy,
                             @RequestParam(defaultValue = "created_at") String sortOrder) {
        try {
            // 查询商品列表
            Map<String, Object> pageData = productService.getProductsByPage(
                    page, size, keyword, categoryId, null, null, null, sortBy, sortOrder);
            
            // 查询分类列表
            List<Category> categories = categoryService.getAllCategories();
            
            model.addAttribute("pageData", pageData);
            model.addAttribute("categories", categories);
            model.addAttribute("keyword", keyword);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortOrder", sortOrder);
            model.addAttribute("currentPage", page);
            model.addAttribute("total", pageData.get("total"));
            model.addAttribute("totalPages", pageData.get("totalPages"));
            model.addAttribute("products", pageData.get("records"));
            
            return "shop/products";
        } catch (Exception e) {
            log.error("查询商品列表失败", e);
            model.addAttribute("error", "查询商品列表失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 分类商品列表页面
     */
    @GetMapping("/category")
    public String categoryProducts(@RequestParam String id,
                                  Model model,
                                  @RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "12") int size,
                                  @RequestParam(required = false) String sortBy,
                                  @RequestParam(defaultValue = "created_at") String sortOrder) {
        try {
            // 查询分类信息
            Category category = categoryService.getCategoryById(id);
            if (category == null) {
                model.addAttribute("error", "分类不存在");
                return "error";
            }
            
            // 查询商品列表
            Map<String, Object> pageData = productService.getProductsByPage(
                    page, size, null, id, null, null, null, sortBy, sortOrder);
            
            // 查询所有分类（用于侧边栏）
            List<Category> categories = categoryService.getAllCategories();
            
            model.addAttribute("category", category);
            model.addAttribute("pageData", pageData);
            model.addAttribute("categories", categories);
            model.addAttribute("categoryId", id);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortOrder", sortOrder);
            model.addAttribute("currentPage", page);
            model.addAttribute("total", pageData.get("total"));
            model.addAttribute("totalPages", pageData.get("totalPages"));
            model.addAttribute("products", pageData.get("records"));
            
            return "shop/category";
        } catch (Exception e) {
            log.error("查询分类商品失败", e);
            model.addAttribute("error", "查询分类商品失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 商品详情页面
     */
    @GetMapping("/product/{id}")
    public String productDetail(@PathVariable String id, Model model) {
        try {
            // 查询商品详情
            Product product = productService.getProductById(id);
            if (product == null) {
                model.addAttribute("error", "商品不存在");
                return "error";
            }
            
            // 查询同类商品推荐
            List<Product> relatedProducts = productService.getRelatedProducts(product.getCategoryId(), id, 4);
            
            // 查询分类的其他商品
            Map<String, Object> categoryPageData = productService.getProductsByPage(1, 5, null, product.getCategoryId(), null, null, null, "created_at", "DESC");
            List<Product> categoryProducts = (List<Product>) categoryPageData.get("records");
            
            model.addAttribute("product", product);
            model.addAttribute("relatedProducts", relatedProducts);
            model.addAttribute("categoryProducts", categoryProducts);
            
            return "shop/product";
        } catch (Exception e) {
            log.error("查询商品详情失败", e);
            model.addAttribute("error", "查询商品详情失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 搜索结果页面
     */
    @GetMapping("/search")
    public String search(Model model,
                        @RequestParam String keyword,
                        @RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "12") int size,
                        @RequestParam(required = false) String categoryId,
                        @RequestParam(required = false) Double minPrice,
                        @RequestParam(required = false) Double maxPrice,
                        @RequestParam(required = false) String sortBy,
                        @RequestParam(defaultValue = "created_at") String sortOrder) {
        try {
            // 查询商品列表
            Map<String, Object> pageData = productService.getProductsByPage(
                    page, size, keyword, categoryId, null, minPrice, maxPrice, sortBy, sortOrder);
            
            // 查询分类列表（用于筛选）
            List<Category> categories = categoryService.getAllCategories();
            
            model.addAttribute("pageData", pageData);
            model.addAttribute("categories", categories);
            model.addAttribute("keyword", keyword);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("minPrice", minPrice);
            model.addAttribute("maxPrice", maxPrice);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortOrder", sortOrder);
            model.addAttribute("currentPage", page);
            model.addAttribute("total", pageData.get("total"));
            model.addAttribute("totalPages", pageData.get("totalPages"));
            model.addAttribute("products", pageData.get("records"));
            
            return "shop/search";
        } catch (Exception e) {
            log.error("搜索商品失败", e);
            model.addAttribute("error", "搜索商品失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 商品分类展示页面
     */
    @GetMapping("/categories")
    public String categories(Model model) {
        try {
            // 查询所有分类
            List<Category> categories = categoryService.getAllCategories();
            
            // 为每个分类添加商品数量
            for (Category category : categories) {
                Map<String, Object> pageData = productService.getProductsByPage(1, 1, null, category.getId(), 1, null, null, null, null);
                int productCount = ((Integer) pageData.get("total")).intValue();
                category.setProductCount(productCount);
            }
            
            model.addAttribute("categories", categories);
            
            return "shop/categories";
        } catch (Exception e) {
            log.error("查询商品分类失败", e);
            model.addAttribute("error", "查询商品分类失败: " + e.getMessage());
            return "error";
        }
    }
}